package sentinel;


//滑动时间窗限流

import java.util.LinkedList;
import java.util.Random;

/**
 2 * 滑动时间窗口限流实现
 3 * 假设某个服务最多只能每秒钟处理100个请求，我们可以设置一个1秒钟的滑动时间窗口，
 4 * 窗口中有10个格子，每个格子100毫秒，每100毫秒移动一次，每次移动都需要记录当前服务请
 求的次数
 5 */
public class Class02_SlidingWindowFlow {
           public long count = 0L;
           public LinkedList<Long> slots = new LinkedList<>();
           public long limit = 100L;
           public boolean flag = false;

            public void doCheck() throws InterruptedException {
                while(true){
                    slots.addLast(count);
                    if(slots.size()>10){
                        slots.removeFirst();
                    }
                    if(slots.peekLast() - slots.peekFirst() > limit){
                        System.out.println("限流了");
                        //todo 修改限流标记true
                        flag = true;
                    }else{
                        //todo 修改限流标记为false
                        flag = false;
                    }
                    Thread.sleep(100L);
                }
            }

    public static void main(String[] args) throws InterruptedException {
        Class02_SlidingWindowFlow SlidingWindowFlow = new Class02_SlidingWindowFlow();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    SlidingWindowFlow.doCheck();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        while(true){
            if(!SlidingWindowFlow.flag){
                SlidingWindowFlow.count++;
            }
             Thread.sleep(new Random().nextInt(10));
        }

    }
}
